package com.foreknow.demo9;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Manager {
    //向文件中写数据
    public void write(List<Student> list, String fileName) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(fileName);
            bw = new BufferedWriter(fw);
            //1.遍历list集合，获取到对象Student
            Iterator<Student> iterator = list.iterator();
            while(iterator.hasNext()) {
                Student stu = iterator.next();
                //2.获取Student对象信息
                String str = stu.getSid()+" "+stu.getName()+" "+stu.getPhone()+" "+stu.getEmail();
                //3.将字符串写到目标文件中
                bw.write(str);
                bw.newLine();
            }
            //4.关闭资源
            bw.close();
            fw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //读取文件中的数据
    public List<Student> readFile(String fileName) {
        FileReader fr = null;
        BufferedReader br = null;
        List<Student> list = new ArrayList<>();
        try {
            fr = new FileReader(fileName);
            br = new BufferedReader(fr);
            //读取文件
            String temp;
            while((temp = br.readLine())!=null) {
                //拆分字符串
                String[] str = temp.split(" ");
                //要将拆分出来的字符串放到Student对象中
                Student s = new Student();
                s.setSid(Integer.parseInt(str[0]));
                s.setName(str[1]);
                s.setPhone(str[2]);
                s.setEmail(str[3]);
                //要将Student对象保存到集合list中
                list.add(s);
            }
            //关闭资源
            br.close();
            fr.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }
}
